package com.company;

import com.company.http.ClientConnection;
import com.company.http.HttpUtils;

import java.io.*;
import java.net.Socket;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: Qwerty
 * Date: 03.10.13
 * Time: 0:04
 * To change this template use File | Settings | File Templates.
 */
public class ClientSession implements Runnable {
    private Socket socket;
    private InputStream in = null;
    private OutputStream out = null;

    private static final String DEFAULT_FILES_DIR = "/www";
    private String tsid = "3CAF7CD0A0BFF";

    public ClientSession(Socket socket) throws IOException {
        this.socket = socket;
        initialize();
    }

    public void initialize() throws IOException {
        in = socket.getInputStream();
        out = socket.getOutputStream();
    }

    public void run() {
        try {
            String header = readHeader();
            /* отображение заголовка запроса */
            System.out.println(header + "\n");
            String url = getURIFromHeader(header);
            System.out.println("Resource: " + url + "\n"); //
            int code = send(url);
            System.out.println("Result code: " + code + "\n"); //
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String readHeader() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder builder = new StringBuilder();
        String ln;
        while(true) {
            ln = reader.readLine();
            if (ln == null || ln.isEmpty()) {
                break;
            }
            builder.append(ln + System.getProperty("line.separator"));
        }
        return builder.toString();
    }

    private String getURIFromHeader(String header) {
        int from = header.indexOf(" ") + 1;
        int to = header.indexOf(" ", from);
        String uri = header.substring(from, to);
        int paramIndex = uri.indexOf("?");
        if (paramIndex != -1) {
            uri = uri.substring(0, paramIndex);
        }
        return DEFAULT_FILES_DIR + uri;
    }

    private int send(String url) throws IOException {
        InputStream strm = Main.class.getResourceAsStream(url);
        int code = (strm != null) ? 200 : 404;
        String header = getHeader(code);
        PrintStream answer = new PrintStream(out, true, "UTF-8");
        answer.print(header);
        if (code == 200) {
            /*int count = 0;
			byte[] buffer = new byte[1024];
			while(( count = strm.read(buffer)) != -1) {
				out.write(buffer, 0, count);
			} */
            strm.close();
            answer.print(ClientConnection.doGet());
        }
        return code;
    }

    private String getHeader(int code) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("HTTP/1.1" + code + " " + getAnswer(code) + "\n");
        buffer.append("Date: " + new Date().toGMTString() + "\n");
	    buffer.append("Set-Cookie: TSID = " + tsid + "\n"); //
        buffer.append("Accept-Ranger: none\n");
        buffer.append("\n");
        return buffer.toString();
    }

    private String getAnswer(int code) {
        switch (code) {
            case 200:
                return "OK";
            case 404:
                return "Not Found";
            default:
                return "Internal Server Error";
        }
    }
}
